package chain;

import java.util.ArrayList;
import java.util.List;

/**
 * @ClassName ChainPatternDemo
 * @Description TODO
 * @Author leejiliang
 * @DateTime 2021/4/6 05:48
 * @Version 1.0
 */
public class ChainPatternDemo {
	public abstract static  class Handler{
		protected Handler handler;

		public Handler(Handler handler) {
			this.handler = handler;
		}
		public abstract void execute();
	}

	static class Handler1 extends Handler{
		public Handler1(Handler handler) {
			super(handler);
		}
		@Override
		public void execute() {
			System.out.println("功能 1");
			if (handler != null) {
				handler.execute();
			}
		}
	}

	static class Handler2 extends Handler{
		public Handler2(Handler handler) {
			super(handler);
		}
		@Override
		public void execute() {
			System.out.println("功能 2");
			if (handler != null) {
				handler.execute();
			}
		}
	}

	static class Handler3 extends Handler{
		public Handler3(Handler handler) {
			super(handler);
		}
		@Override
		public void execute() {
			System.out.println("功能 3");
			if (handler != null) {
				handler.execute();
			}
		}
	}

	public static void main(String[] args) {
//		Handler3 handler3 = new Handler3(null);
//		Handler2 handler2 = new Handler2(handler3);
//		Handler1 handler1 = new Handler1(handler2);

//		handler1.execute();

		Handler2 handler2 = new Handler2(null);
		Handler3 handler3 = new Handler3(handler2);
		Handler1 handler1 = new Handler1(handler3);
//
//		handler1.execute();



		HandlerChain.addHandler(handler1);
		HandlerChain.addHandler(handler2);
		HandlerChain.addHandler(handler3);
		HandlerChain.process();



	}

	static class HandlerChain{
		private static List<Handler> handlers = new ArrayList<>();

		public static void addHandler(Handler handler) {
			handlers.add(handler);
		}

		public static void process() {
			handlers.forEach(Handler::execute);
		}
	}
}
